from flask import Blueprint, request

from controllers import R
from mauth import HasPerm
from services.rbac_service import RbacService

# 声明一个蓝图
rbac = Blueprint("rbac", __name__, url_prefix="/sys/rbac")
# 声明一个RBAC业务服务
rbac_service = RbacService()


@rbac.route("/roleMenuIds", methods=["POST"])
@HasPerm(
    access="sys:rbac:roleMenuIds,sys:rbac:saveRoleMenu",
    name="获取角色菜单ID列表",
    mode="or",
)
def roleMenuIds():
    """
    获取角色菜单ID列表
    :return:
    """
    roleId = request.json.get("roleId")
    return R.data(rbac_service.role_menu_ids(roleId))


@rbac.route("/saveRoleMenu", methods=["POST"])
@HasPerm(access="sys:rbac:saveRoleMenu", name="添加角色菜单", mode="or")
def save_role_menu():
    """
    添加角色菜单
    :return:
    """
    rbac_service.save_role_menu(request.json)
    return R.success()


@rbac.route("/userListByRoleId", methods=["POST"])
@HasPerm(access="sys:rbac:userListByRoleId", name="通过角色ID获取用户列表")
def user_list_by_role_id():
    """
    通过角色ID获取用户列表
    :return:
    """
    json = request.json
    roleId = json.get("roleId")
    keywords = json.get("keywords")
    pageNum = json.get("pageNum")
    pageSize = json.get("pageSize")
    return R.data(
        rbac_service.user_list_by_role_id(
            roleId=roleId, keywords=keywords, pageNum=pageNum, pageSize=pageSize
        )
    )


@rbac.route("/removeUserRole", methods=["POST"])
@HasPerm(access="sys:rbac:removeUserRole", name="删除用户角色关系")
def remove_user_role():
    """
    删除用户角色关系
    :return:
    """
    userRoles = request.json
    rbac_service.remove_user_role(userRoles)
    return R.success()


@rbac.route("/userListExcludeRoleId", methods=["POST"])
@HasPerm(access="sys:rbac:userListExcludeRoleId", name="获取用户列表-排除指定角色")
def user_list_exclude_role_id():
    """
    获取用户列表-排除指定角色
    :return:
    """
    json = request.json
    roleId = json.get("roleId")
    keywords = json.get("keywords")
    pageNum = json.get("pageNum")
    pageSize = json.get("pageSize")
    return R.data(
        rbac_service.user_list_exclude_role_id(
            roleId=roleId, keywords=keywords, pageNum=pageNum, pageSize=pageSize
        )
    )


@rbac.route("/saveUserRole", methods=["POST"])
@HasPerm(access="sys:rbac:saveUserRole", name="添加用户角色关系")
def save_user_role():
    """
    添加用户角色关系
    :return:
    """
    userRoles = request.json
    rbac_service.save_user_role(userRoles)
    return R.success()
